package com.hushao.aimi.service.impl;

import com.hushao.aimi.DateUtil;
import com.hushao.aimi.common.PageVo;
import com.hushao.aimi.common.ServerResponse;
import com.hushao.aimi.entity.Role;
import com.hushao.aimi.entity.UserRole;
import com.hushao.aimi.bo.UserBo;
import com.hushao.aimi.vo.UserVo;
import com.hushao.aimi.repository.RoleRepository;
import com.hushao.aimi.repository.UserRepository;
import com.hushao.aimi.repository.UserRoleRepository;
import com.hushao.aimi.service.UserService;

import com.hushao.aimi.entity.AimiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @description: 用户服务
 * @author: 胡少
 * @create: 2018-06-03 21:36
 **/

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private RoleRepository roleRepository;
    @Override
    public ServerResponse findAllByUsernameLike(String username, Pageable pageable) {
        username="%"+username+"%";
        Page<Object> page=userRepository.findUserByUsernameLike(username,pageable);
        List<UserVo> userVos=page.getContent().stream().map(
                UserBo::new).map(u2->new UserVo(u2.getId(),
                u2.getUsername(),
                u2.getPhone(),
                u2.getEmail(),
                u2.getStatus(),
                u2.getRoleId(),
                DateUtil.getDateTimeOfTimestamp(u2.getCreateTime()),
                DateUtil.getDateTimeOfTimestamp(u2.getUpdateTime())))
                .collect(Collectors.toList());
        PageVo pageVo=new PageVo(page);
        Map<String,Object> map=new HashMap<>(2);
        map.put("page",pageVo);
        map.put("users",userVos);
        return ServerResponse.Success(map);
    }

    @Override
    public ServerResponse getUser(String username) {
        Optional<AimiUser> optional=Optional.ofNullable(userRepository.findByUsername(username));
        if(optional.isPresent()){
            AimiUser user=optional.get();
            List<Role> roles=roleRepository.listRoleByUser(user.getId());
        }
       return ServerResponse.Error("未知错误");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse addUser(UserVo userVo)throws Exception{
        AimiUser user=new AimiUser(userVo.getUsername(),userVo.getPassword(),userVo.getPhone(),null);
        AimiUser aimiUser=userRepository.save(user);
        log.info("添加用户：{}成功",user.getUsername());

        userRoleRepository.save(new UserRole(aimiUser.getId(),userVo.getRoleId(),null));
        log.info("添加权限成功");
        userVo.setId(aimiUser.getId());
        userVo.setStatus(aimiUser.getStatus());
        userVo.setCreateTime(DateUtil.getDateTimeOfTimestamp(aimiUser.getCreateTime()));
        userVo.setUpdateTime(DateUtil.getDateTimeOfTimestamp(aimiUser.getUpdateTime()));
        return ServerResponse.Success("添加用户成功",userVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse delUser(String userId)throws Exception{
        userRepository.deleteById(userId);
        userRoleRepository.delByUserId(userId);
        log.info("删除用户及权限成功：{}",userId);
        return ServerResponse.Success("删除用户成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse update( UserVo userVo)throws Exception {
        Optional<AimiUser> optional=userRepository.findById(userVo.getId());
        UserRole userRole=userRoleRepository.findByUserId(userVo.getId());
        if(optional.isPresent()){
            AimiUser user=optional.get();
            user.setUsername(userVo.getUsername());
            user.setPhone(userVo.getPhone());
            user.setEmail(userVo.getEmail());
            user.setStatus(userVo.getStatus());
            userRepository.flush();

            if(!userRole.getRoleId().equals(userVo.getRoleId())){
                userRole.setRoleId(userVo.getRoleId());
                userRoleRepository.save(userRole);
            }
        }else {
            new RuntimeException("错误");
        }
        log.info("修改用户：{}成功",userVo.getUsername());
        return ServerResponse.Success("修改用户成功");
    }

    @Override
    public Long count() {
        return userRepository.count();
    }

}
